#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "delay.h"
#include "mh2203.h"
#include "w25qxx.h"	 

#define PRINTF_LOG 	printf


#define USART_SET   USART2
USART_TypeDef* USART_TEST = USART_SET;

void UART_Configuration(uint32_t bound);
void GPIO_Configuration(void);
void RCC_ClkConfiguration(void);
// void Test(void);
#define BUFFSIZE 1024 
uint8_t Rx_Buff[BUFFSIZE];
uint8_t read_buffer[256];

uint32_t DMA_Recive_Num=0, total_data_written = 0;
uint8_t Recive=0;
uint32_t Write_ADDR=0;
u8 TEXT_Buffer[]={0x01,0x02,0x04,0x08};
#define SIZE sizeof(TEXT_Buffer)
void USART_DMA_Init(void);

uint32_t FLASH_SIZE=128*1024*1024;	//FLASH 大小为16M字节
uint8_t datatemp[SIZE];

int main(void)
{	
	RCC_ClocksTypeDef clocks;

	
	RCC_ClkConfiguration();
	Delay_Init();
	UART_Configuration(256000);
	USART_DMA_Init();
	RCC_GetClocksFreq(&clocks);
	
	PRINTF_LOG("\n");
	PRINTF_LOG("SYSCLK: %3.1fMhz, HCLK: %3.1fMhz, PCLK1: %3.1fMhz, PCLK2: %3.1fMhz\n", \
	(float)clocks.SYSCLK_Frequency/1000000, (float)clocks.HCLK_Frequency/1000000, \
	(float)clocks.PCLK1_Frequency/1000000, (float)clocks.PCLK2_Frequency / 1000000);
	PRINTF_LOG("SPI FLASH Test.\n");
	
	W25QXX_Init();	
	while(W25QXX_ReadID()!=W25Q128)								//检测不到
	{
		PRINTF_LOG("W25Q128 Check Failed!\n");
		PRINTF_LOG("Read ID: 0x%x\n",W25QXX_ReadID());
		Delay_Ms(2000);
	}
	W25QXX_Erase_Chip();
//   PRINTF_LOG("Erase Ok!\n");
//   DMA_Cmd(DMA1_Channel5, ENABLE);
	DMA_Cmd(DMA1_Channel6, ENABLE);
	while(1)
	{
		if(Recive==1)
		{
			W25QXX_Write(Rx_Buff,Write_ADDR,DMA_Recive_Num);
			Write_ADDR+=DMA_Recive_Num;

            total_data_written += DMA_Recive_Num; // 更新已写入的总数据量
            // PRINTF_LOG("Total data written: %u bytes\n", total_data_written); // 打印已写入的总数据量
			DMA_Recive_Num=0;
		  Recive=0;
		}
		if(Recive==2)
		{
			W25QXX_Read(read_buffer,0,256);
		}

		// W25QXX_Read(read_buffer,0,256);					//从倒数第100个地址处开始,读出SIZE个字节
		// PRINTF_LOG("The Data Readed Is:  \n");				//提示传送完成
		// PRINTF_LOG("%s\n",read_buffer);
		// Delay_Ms(2000);
		
		// Test();
	}
}
void USART1_IRQHandler(void)
{
    if(USART_GetITStatus(USART1,USART_IT_IDLE)==SET)
    {
		DMA_Recive_Num=BUFFSIZE-DMA_GetCurrDataCounter(DMA1_Channel5);
        DMA_Cmd(DMA1_Channel5, DISABLE);
		DMA_SetCurrDataCounter(DMA1_Channel5,1024);
        DMA_Cmd(DMA1_Channel5,ENABLE);
        Recive=1;
        USART1->SR;
        USART1->DR;
    }
} 


void USART2_IRQHandler(void)
{
    if(USART_GetITStatus(USART2,USART_IT_IDLE)==SET)
    {
		DMA_Recive_Num=BUFFSIZE-DMA_GetCurrDataCounter(DMA1_Channel6);
        DMA_Cmd(DMA1_Channel6, DISABLE);
		DMA_SetCurrDataCounter(DMA1_Channel6,1024);
        DMA_Cmd(DMA1_Channel6,ENABLE);
        Recive=1;
        USART2->SR;
        USART2->DR;
    }
} 

// void Test(void)
// {
// 	int i = 0;
// 	PRINTF_LOG("Start Write W25Q64....\n"); 
// 	TEXT_Buffer[0] = TEXT_Buffer[0]+1;
// 		W25QXX_Write((u8*)TEXT_Buffer, FLASH_SIZE-100, SIZE);			//从倒数第100个地址处开始,写入SIZE长度的数据
// 		PRINTF_LOG("W25Q128 Write Finished!\n");	//提示传送完成
// 		Delay_Ms(2000);
// 		PRINTF_LOG("Start Read W25Q64.... \n");
		// W25QXX_Read(datatemp,FLASH_SIZE-100,SIZE);					//从倒数第100个地址处开始,读出SIZE个字节
// 		PRINTF_LOG("The Data Readed Is:  \n");	//提示传送完成
// 		for (i = 0; i < SIZE; i++) {
// 			printf("%02X ", datatemp[i]); //以十六进制格式打印数据
// 		}
// 		printf("\n");
// 		Delay_Ms(2000);
//   }

void RCC_ClkConfiguration(void)
{
	// RCC_DeInit();

	// RCC_HSEConfig(RCC_HSE_ON);
	// while(RCC_GetFlagStatus(RCC_FLAG_HSERDY) == RESET);
	
	// RCC_PLLCmd(DISABLE);
	
	// FLASH_SetLatency(FLASH_Latency_2);
	
	// RCC_PLLConfig(RCC_PLLSource_HSE_Div1,RCC_PLLMul_9);
	
	// RCC_PLLCmd(ENABLE);
	// while(RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET);
	
	// RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK);
	
	// RCC_HCLKConfig(RCC_SYSCLK_Div1);
	// RCC_PCLK1Config(RCC_HCLK_Div2);
	// RCC_PCLK2Config(RCC_HCLK_Div1);
	
	// RCC_LSICmd(ENABLE);
	// while(RCC_GetFlagStatus(RCC_FLAG_LSIRDY) == RESET);
	// RCC_HSICmd(ENABLE);
	// while(RCC_GetFlagStatus(RCC_FLAG_HSIRDY) == RESET);

	RCC_DeInit();

	RCC_HSICmd(ENABLE);
	while(RCC_GetFlagStatus(RCC_FLAG_HSIRDY) == RESET);         //等待HSI准备好

	RCC_PLLCmd(DISABLE);

	FLASH_SetLatency(FLASH_Latency_2);

	RCC_PLLConfig(RCC_PLLSource_HSI_Div1,RCC_PLLMul_9);     // 8 * 32 = 256MHZ

	RCC_PLLCmd(ENABLE);
	while(RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET);

	RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK);

	RCC_HCLKConfig(RCC_SYSCLK_Div1);
	RCC_PCLK1Config(RCC_HCLK_Div2);
	RCC_PCLK2Config(RCC_HCLK_Div1);

	RCC_LSICmd(ENABLE);
	while(RCC_GetFlagStatus(RCC_FLAG_LSIRDY) == RESET);
	
}



void UART_Configuration(uint32_t bound)
{
	GPIO_InitTypeDef GPIO_InitStructure;
	USART_InitTypeDef USART_InitStructure;
  	NVIC_InitTypeDef NVIC_InitStructure;
	

    if (USART_SET == USART2) {
        RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2,ENABLE);
        RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);

        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
        GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
        GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
        GPIO_Init(GPIOA, &GPIO_InitStructure);

        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;
        GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
        GPIO_Init(GPIOA, &GPIO_InitStructure);

		NVIC_InitStructure.NVIC_IRQChannel=USART2_IRQn;
		NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE;
		NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=0;
		NVIC_InitStructure.NVIC_IRQChannelSubPriority=0;
		NVIC_Init(&NVIC_InitStructure);

        USART_InitStructure.USART_BaudRate = bound;
        USART_InitStructure.USART_WordLength = USART_WordLength_8b;
        USART_InitStructure.USART_StopBits = USART_StopBits_1;
        USART_InitStructure.USART_Parity = USART_Parity_No;
        USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
        USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;

		USART_Init(USART_TEST, &USART_InitStructure);
		USART_ITConfig(USART_TEST,USART_IT_IDLE,ENABLE);
		USART_DMACmd(USART_TEST,USART_DMAReq_Rx,ENABLE);
		USART_Cmd(USART_TEST, ENABLE);
		USART_DMA_Init();
    } else if (USART_SET == USART1) {
        RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);
        RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
        GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
        GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
        GPIO_Init(GPIOA, &GPIO_InitStructure);

        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
        GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
        GPIO_Init(GPIOA, &GPIO_InitStructure);

		NVIC_InitStructure.NVIC_IRQChannel=USART1_IRQn;
		NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE;
		NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=0;
		NVIC_InitStructure.NVIC_IRQChannelSubPriority=0;
		NVIC_Init(&NVIC_InitStructure);

	
        USART_InitStructure.USART_BaudRate = bound;
        USART_InitStructure.USART_WordLength = USART_WordLength_8b;
        USART_InitStructure.USART_StopBits = USART_StopBits_1;
        USART_InitStructure.USART_Parity = USART_Parity_No;
        USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
        USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;

		USART_Init(USART_TEST, &USART_InitStructure);
		USART_ITConfig(USART_TEST,USART_IT_IDLE,ENABLE);
		USART_DMACmd(USART_TEST,USART_DMAReq_Rx,ENABLE);
		USART_Cmd(USART_TEST, ENABLE);
		USART_DMA_Init();
    }
	
}
void USART_DMA_Init(void)
{
	 DMA_InitTypeDef DMA_InitStructure;

	if (USART_SET == USART2) {
		RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE);
		DMA_Cmd(DMA1_Channel6, DISABLE); //jieshou
		//USART1_RX DMA Config
		DMA_DeInit(DMA1_Channel6);
		DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t )&USART2->DR;
		DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t )Rx_Buff;
		DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC;
		DMA_InitStructure.DMA_BufferSize = BUFFSIZE;
		DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
		DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
		DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte;
		DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;
		DMA_InitStructure.DMA_Mode = DMA_Mode_Normal;
		DMA_InitStructure.DMA_Priority = DMA_Priority_Medium;
		DMA_InitStructure.DMA_M2M = DMA_M2M_Disable;
		DMA_Init(DMA1_Channel6, &DMA_InitStructure);

	} else if (USART_SET == USART1) {
		RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE);
		DMA_Cmd(DMA1_Channel5, DISABLE); //jieshou
		//USART1_RX DMA Config
		DMA_DeInit(DMA1_Channel5);
		DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t )&USART1->DR;
		DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t )Rx_Buff;
		DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC;
		DMA_InitStructure.DMA_BufferSize = BUFFSIZE;
		DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
		DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
		DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte;
		DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;
		DMA_InitStructure.DMA_Mode = DMA_Mode_Normal;
		DMA_InitStructure.DMA_Priority = DMA_Priority_Medium;
		DMA_InitStructure.DMA_M2M = DMA_M2M_Disable;
		DMA_Init(DMA1_Channel5, &DMA_InitStructure);
	}	
}


void flash_dump(uint32_t addr, uint16_t len)
{
    uint8_t buf[16];
    uint16_t i, j;

    printf("\r\nFlash dump from 0x%08X, length: %d bytes\r\n", addr, len);

    for(i = 0; i < len; i += 16)
    {
        // 读取16字节数据
        W25QXX_Read(buf, addr + i, (len-i)>=16 ? 16 : (len-i));

        // 打印地址
        printf("0x%08X: ", addr + i);

        // 打印十六进制数据
        for(j = 0; j < 16; j++)
        {
            if((i + j) < len)
            {
                printf("%02X ", buf[j]);
            }
            else
            {
                printf("   ");
            }
        }

        // 打印ASCII字符
        printf(" |");
        for(j = 0; j < 16; j++)
        {
            if((i + j) < len)
            {
                if(buf[j] >= 0x20 && buf[j] <= 0x7E)
                {
                    printf("%c", buf[j]);
                }
                else
                {
                    printf(".");
                }
            }
            else
            {
                printf(" ");
            }
        }
        printf("|\r\n");
    }
}

int SER_PutChar (int ch)
{
	while(!USART_GetFlagStatus(USART_TEST,USART_FLAG_TC));
	USART_SendData(USART_TEST, (uint8_t) ch);

	return ch;
}

int fputc(int c, FILE *f)
{
	/* Place your implementation of fputc here */
	/* e.g. write a character to the USART */
	if (c == '\n')
	{
		SER_PutChar('\r');
	}
	return (SER_PutChar(c));
}

